/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clientClasses;

import commonClasses.*;
import commonClasses.commonInterfaces.ClientModelIntf;
import commonClasses.commonInterfaces.ItemIntf;
import commonClasses.commonInterfaces.ServerIntf;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author Pozytywny!
 */
public class ClientModel implements ClientModelIntf {

    private String _identifier = null;
    //ipserwera -> port -> rzeczy z tego servera
    private ArrayList<ServerIntf> _servers = new ArrayList<ServerIntf>();

    public String getIdentifier() {
        return _identifier;
    }

    public void setIdentifier(String ident) {
        _identifier = ident;
    }

    public ArrayList<ItemIntf> getServerItems(InetAddress ip, int port) throws
            Exception {

        ServerIntf server = getServerByAddAndPort(ip, port);
        if (server == null) {
            throw new Exception("given server not found");
        }

        return server.getItems();
    }

    public ServerIntf getServerByAddAndPort(InetAddress ip, int port) {
        Iterator<ServerIntf> it = _servers.iterator();

        while (it.hasNext()) {
            ServerIntf server = it.next();
            if (server.getInetAddress().equals(ip) && server.getPort() == port) {
                return server;
            }
        }
        return null;

    }

    public ArrayList<ServerIntf> getServers() {
        return _servers;
    }

    public void updateSerwerItem(InetAddress ip, int port, ItemIntf item) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void updateSerwerItemPrice(InetAddress ip, int port, ItemIntf item) {

        ServerIntf server = getServerByAddAndPort(ip, port);
        if (server.getInetAddress().equals(ip) && server.getPort() == port) {
            server.getItemByID(item.getId()).setItemPrice(item.getPrice());
        }

    }

    public void updateSerwerItems(InetAddress ip, int port,
            ArrayList<ItemIntf> itemList) {

        ServerIntf server = getServerByAddAndPort(ip, port);
        if(server != null) server.setItems(itemList);
        else Utils.write("server == null..");
    }

    public void updateSerwerItemFiles(InetAddress ip, int port, Long itemID,
            ArrayList<String> fileList) {
        ServerIntf server = getServerByAddAndPort(
                ip,
                port);
        ItemIntf item = null;
        if (server != null) {
            item = server.getItemByID(itemID);
            if (item != null) {
                item.addFilePaths(fileList);
            } else {
                Utils.write("Item not found!");
            }
        } else {
            Utils.write("given host not found");
        }
    }
}
